package com.tjvib.view.activity;

import static com.tjvib.Constants.SUCCESS;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

import com.tjvib.R;
import com.tjvib.base.BaseActivity;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.DataSetManager;
import com.tjvib.presenter.BasePresenter;
import com.tjvib.sensor.SensorData;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.view.dialog.LoadingDialog;
import com.tjvib.widget.AndroidScheduler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class ParamActivity extends BaseActivity {

    private Button param_btn_next;
    private Spinner param_sp_peo, param_sp_peodir, param_sp_stru, param_tv_std;
    private EditText param_et_hz, param_et_znb, param_et_tz, param_et_dm, param_et_lr;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_param;
    }

    @Override
    protected boolean initView() {
        param_btn_next = findViewById(R.id.param_btn_next);
        param_btn_next.setOnClickListener(v -> {
            if (param_sp_peo.getSelectedItem() != null &&
                    param_sp_peodir.getSelectedItem() != null &&
                    param_sp_stru.getSelectedItem() != null &&
                    param_tv_std.getSelectedItem() != null &&
                    !param_et_hz.getText().toString().isEmpty() &&
                    !param_et_znb.getText().toString().isEmpty() &&
                    !param_et_tz.getText().toString().isEmpty() &&
                    !param_et_dm.getText().toString().isEmpty() &&
                    !param_et_lr.getText().toString().isEmpty()) {
                if (Integer.parseInt(param_et_lr.getText().toString()) <= 1) {
                    showErrorDialog("测量范围输入要大于1！");
                } else if (param_sp_peo.getSelectedItem().toString()
                        .equals(param_sp_stru.getSelectedItem().toString())) {
                    showErrorDialog("人体测传感器不能与结构侧传感器相同！");
                } else {
                    int humanImuId = Integer.parseInt(param_sp_peo.getSelectedItem().toString());
                    int humanDirection = param_sp_peodir.getSelectedItemPosition();
                    int structureImuId = Integer.parseInt(param_sp_stru.getSelectedItem().toString());
                    int structureDirection = param_tv_std.getSelectedItemPosition();
                    float natureFrequency = Float.parseFloat(param_et_hz.getText().toString());
                    float dampingRatio = Float.parseFloat(param_et_znb.getText().toString());
                    float humanWeight = Float.parseFloat(param_et_tz.getText().toString());
                    float deltaMass = Float.parseFloat(param_et_dm.getText().toString());
                    int loopRange = Integer.parseInt(param_et_lr.getText().toString());
                    requestTask(humanImuId, humanDirection, structureImuId, structureDirection,
                            natureFrequency, dampingRatio, humanWeight, deltaMass, loopRange);
                }
            } else {
                showErrorDialog("请输入完整参数！");
            }
        });

        param_sp_peo = findViewById(R.id.param_sp_peo);
        param_sp_peodir = findViewById(R.id.param_sp_peodir);
        param_sp_stru = findViewById(R.id.param_sp_stru);
        param_tv_std = findViewById(R.id.param_tv_std);

        param_et_hz = findViewById(R.id.param_et_hz);
        param_et_znb = findViewById(R.id.param_et_znb);
        param_et_tz = findViewById(R.id.param_et_tz);
        param_et_dm = findViewById(R.id.param_et_dm);
        param_et_lr = findViewById(R.id.param_et_lr);

        return true;
    }

    @Override
    protected boolean initData() {
        String[] directions = {"X", "Y", "Z"};
        SpinnerAdapter directionSpinnerAdapter = new ArrayAdapter<>(this,
                R.layout.item_spinner_dropdown, directions);
        SpinnerAdapter sensorSpinnerAdapter = new ArrayAdapter<>(this,
                R.layout.item_spinner_dropdown, DataSetManager.getInstance().getSensorList());

        param_sp_peo.setAdapter(sensorSpinnerAdapter);
        param_sp_peodir.setAdapter(directionSpinnerAdapter);
        param_sp_stru.setAdapter(sensorSpinnerAdapter);
        param_tv_std.setAdapter(directionSpinnerAdapter);

        return true;
    }

    @Override
    protected BasePresenter genPresenter() {
        return null;
    }


    private String getRequestTask(String acc, float dampingRatio, String dataSetId,
                                  float deltaMass, float humanWeight, int loopRange,
                                  float natureFrequency, String response) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("acc", acc);
        map.put("dampingRatio", dampingRatio);
        map.put("dataSetId", dataSetId);
        map.put("deltaMass", deltaMass);
        map.put("humanWeight", humanWeight);
        map.put("loopRange", loopRange);
        map.put("natureFrequency", natureFrequency);
        map.put("response", response);

        LogUtil.e("getRequestTask: map json:" + new JSONObject(map));
        return new JSONObject(map).toString();
    }


    private void requestTask(int humanImuId, int humanDirection, int structureImuId, int structureDirection,
                             float natureFrequency, float dampingRatio, float humanWeight, float deltaMass, int loopRange) {

        List<? extends SensorData> humanDataList = DataSetManager.getInstance().getDataSetContent(humanImuId);
        List<? extends SensorData> structureDataList = DataSetManager.getInstance().getDataSetContent(structureImuId);

        ArrayList<Float> acc = new ArrayList<>();
        for (SensorData data : humanDataList) {
            acc.add(data.acc[humanDirection]);
        }

        ArrayList<Float> response = new ArrayList<>();
        for (SensorData data : structureDataList) {
            response.add(data.acc[structureDirection]);
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),
                getRequestTask(new JSONArray(acc).toString(), dampingRatio,
                        "" + DataSetManager.getInstance().getDataSetInfo().getId(),
                        deltaMass, humanWeight, loopRange, natureFrequency, new JSONArray(response).toString()));
        LoadingDialog loadingDialog = new LoadingDialog(ParamActivity.this);
        loadingDialog.showDialog(ParamActivity.this, "正在请求操作…");
        RetrofitHelper.getInstance().create()
                .hs_compute(requestBody, "" + UserManager.getInstance().getUserId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse value) {
                        if (value.getCode() == SUCCESS) {
                            try {
                                JSONObject jsonObject = new JSONObject(String.valueOf(value.getData()));
                                double rmsResponse = jsonObject.getDouble("rmsResponse");
                                JSONArray jsonArray = jsonObject.getJSONArray("simuRMS");
                                double[] simuRMS = new double[jsonArray.length()];
                                for (int i = 0; i < jsonArray.length(); i++)
                                    simuRMS[i] = jsonArray.getDouble(i);
//                                setResult(loopRange, deltaMass, rmsResponse, simuRMS);
                                Intent intent = new Intent(ParamActivity.this, HumanActivity.class);
                                intent.putExtra("METHOD", getIntent().getStringExtra("METHOD"));
                                intent.putExtra("loopRange", loopRange);
                                intent.putExtra("deltaMass", deltaMass);
                                intent.putExtra("rmsResponse", rmsResponse);
                                intent.putExtra("simuRMS", simuRMS);
                                ParamActivity.this.startActivity(intent);
                            } catch (JSONException e) {
                                showErrorDialog("解析服务器数据失败");
                            }
                        } else {
                            showErrorDialog(value.getMessage());
                        }
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        loadingDialog.dismiss();
                        ToastUtil.show(e.getMessage());
                        LogUtil.e(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
}